import org.junit.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTrans {

    private static Connection getConn() throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
        String username = "root";
        String password="123456";
        //1、通过反射加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2、连接数据库
        return DriverManager.getConnection(url, username, password);
    }
    private Connection connection;


    @Before
    public void setUp() throws ClassNotFoundException, SQLException {

        connection = getConn();
        System.out.println("init  "+connection);
    }
    @Test
    public void testTrans() throws SQLException {
        System.out.println(connection);
        //关闭自动提交
        connection.setAutoCommit(false);

        try{
            String sql = "update account set balance=balance-100 where id=1";
            connection.prepareStatement(sql).executeUpdate();
            System.out.println(1/0);
            connection.commit();
        }catch (Exception e){
            connection.rollback();
        }

    }

    @After
    public void tearDown() throws SQLException {
        System.out.println("destory  "+connection);
        connection.close();

    }
}
